/**
 * 描述: jwt-token验证和解析函数
 * 作者: txm
 * 日期: 2024-08-05
 */
const jwt = require("jsonwebtoken"); // 引入验证jsonwebtoken模块
const { PRIVATE_KEY } = require("./constant"); // 引入自定义的jwt密钥

// jwt-token解析
const verify = (req, res, next) => {
  try {
    let authorization = req.headers.authorization.split(" ")[1];
    const decoded = jwt.verify(authorization, PRIVATE_KEY);
    req.getToken = () => decoded;
    next();
  } catch (err) {
    res.status(401).json({
      code: 401,
      msg: "token失效，请重新登录",
      data: null,
    });
  }
};

module.exports = {
  verify,
};
